package com.gss.plugin.kafka.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * 获取当前服务器ip地址
 */
public class IpAddressUtil {


    /**
     * 获取本地IP地址
     *
     * @throws Exception
     */
    public static String getLocalIP(){
        try {
            if (isWindowsOS()) {
                return InetAddress.getLocalHost().getHostAddress();
            } else {
                return getLinuxLocalIp();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取当前服务器ip出错，则默认返回127.0.0.1
        return "127.0.0.1";
    }


    /**
     * 获取Linux下的IP地址
     *
     * @return IP地址
     * @throws Exception
     */
    private static String getLinuxLocalIp() throws Exception {
        String ip = "";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                String name = intf.getName();
                if (name.contains("docker") || name.contains("lo")) {
                    continue;
                }
                //获取网卡ip
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (inetAddress.isLoopbackAddress()) {
                        continue;
                    }

                    String ipaddress = inetAddress.getHostAddress().toString();
                    if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                        ip = ipaddress;
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return ip;
    }


    /**
     * 判断操作系统是否是Windows
     *
     * @return
     */
    public static boolean isWindowsOS() {
        boolean isWindowsOS = false;
        String osName = System.getProperty("os.name");
        if (osName.toLowerCase().indexOf("windows") > -1) {
            isWindowsOS = true;
        }
        return isWindowsOS;
    }

}
